<?php

namespace Xibeicity\Message\Controllers;

use think\Request;
use think\facade\Db;
use Xibeicity\Message\Database\MessageLogger;

class MessageController
{
    /**
     * 获取消息列表
     *
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request)
    {
        $query = Db::name('message_logs');

        // 筛选条件
        $driver = $request->param('driver');
        if ($driver) {
            $query->where('driver', $driver);
        }
        
        $status = $request->param('status');
        if ($status) {
            $query->where('status', $status);
        }
        
        $to = $request->param('to');
        if ($to) {
            $query->where('to', $to);
        }

        // 排序
        $query->order('created_at', 'desc');

        // 分页
        $perPage = $request->param('per_page', 15);
        $messages = $query->paginate($perPage);

        // 根据请求类型返回不同格式的数据
        if ($request->isAjax()) {
            return json([
                'code' => 0,
                'message' => 'success',
                'data' => $messages
            ]);
        }

        // 传统模式返回视图
        return view('message/list', ['messages' => $messages]);
    }
}